<template>
  <el-select
    v-model="currentID"
    v-loadMore="selectLoadMore"
    filterable
    remote
    :placeholder="placeholder"
    clearable
    @change="handleChange"
    :remote-method="remoteMethod"
    :loading="loading"
    @visible-change="visibleChange"
    :disabled="disabled"
  >
    <el-option
      v-for="item in options"
      :key="item.id"
      :label="item.dname"
      :value="item.id"
    ></el-option>
  </el-select>
</template>

<script>
import { getChannelLists } from "@/api/channel/channel.js";
import { arrayUnique } from '@/utils/ruoyi'

export default {
  props: {
    defaultValue: {
      type: Number | String
    },
    placeholder: {
      type: String,
      default: '请选择渠道'
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  watch: {
    defaultValue(nval){
      this.currentID = nval;
    }
  },
  data() {
    return {
      currentID: null,
      options: [],
      getParams: {
        pageNum: 1,
        pageSize: 9999,
        searchValue: undefined,
      },
      total: 0,
      loading: false
    };
  },
  async created() {
    this.currentID = this.defaultValue;
    await this.getListCompany();
  },
  methods: {
    /** 查询渠道列表 */
    async getListCompany() {
      const { data } = await getChannelLists({...this.getParams});
      this.total = data.length;
      if(this.getParams.pageNum === 1){ this.options = [] };
      this.options = arrayUnique([...data], 'id');
    },
    // 下拉加载更多
    selectLoadMore() {
      if(this.options.length < this.total){
        this.getParams.pageNum++;
        this.getListCompany();
      }
    },
    visibleChange(e){
      if(!e){
        this.remoteMethod('')
      }
    },
    async remoteMethod(query){
      this.loading = true;
      this.getParams.pageNum = 1;
      this.getParams.pageSize = 9999;
      this.getParams.searchValue = query;
      await this.getListCompany();
      this.loading = false;
    },
    handleChange(e){
      this.$emit('update:defaultValue', e);
      this.$emit('change', e);
    }
  },
};
</script>

<style lang="scss" scoped></style>
